package com.example.hello.service.impl;

import com.example.hello.mapper.SMSCodeMapper;
import com.example.hello.mapper.UserMapper;
import com.example.hello.pojo.SMSCode;
import com.example.hello.pojo.User;
import com.example.hello.service.ResetPasswordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class ResetPasswordServiceImpl implements ResetPasswordService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SMSCodeMapper smsCodeMapper;

    // 用于密码加密的 BCrypt 加密器
    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    @Transactional
    public boolean resetPassword(String phone, String smsCode, String newPassword) {
        // 1. 查询用户是否存在
        User user = userMapper.findByPhone(phone);
        if (user == null) {
            throw new RuntimeException("该手机号未注册");
        }
        
        // 2. 查询该手机号最新的验证码记录
        SMSCode latestCode = smsCodeMapper.getLatestCodeByPhone(phone);
        if (latestCode == null) {
            throw new RuntimeException("验证码不存在，请重新发送验证码");
        }
        
        // 3. 校验验证码
        Date now = new Date();
        if (!latestCode.getCode().equals(smsCode)) {
            throw new RuntimeException("验证码不正确");
        }
        if (now.after(latestCode.getExpireTime())) {
            throw new RuntimeException("验证码已过期");
        }
        if (latestCode.getStatus() != 0) {
            throw new RuntimeException("验证码已使用");
        }
        
        // 4. 将验证码状态更新为已使用
        smsCodeMapper.updateStatus(latestCode.getId());
        
        // 5. 加密新密码并更新用户记录
        String encodedPassword = passwordEncoder.encode(newPassword);
        int updateCount = userMapper.updatePasswordByPhone(phone, encodedPassword);
        if (updateCount > 0) {
            return true;
        }
        return false;
    }
}